package com.soos.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * Created with IntelliJ IDEA.
 * Description: 全局唯一id生成器
 * 全局唯一id生成器,主要用于生成唯一id
 * User: sfx
 * Date: 2023-06-27
 * Time: 20:13
 */
@Component
public class RedisWorker {
    private StringRedisTemplate stringRedisTemplate;

    public RedisWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    private static final long BEGIN_TIMESTAMP = 1672531200L;

    private static final long COUNT_BIT = 32L;

    public long nextId(String prefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long time = now.toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMP;
        //生成序列号
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long id = stringRedisTemplate.opsForValue().increment("icr:" + prefix + ":" + format);
        //进行拼接
        return (time << COUNT_BIT) | id;
    }
}